﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;

namespace BtSearcher
{
    public partial class MainForm : TX.Framework.WindowUI.Forms.BaseForm
    {
        private string ToUTF8Str(string html)
        {
            byte[] buf = Encoding.UTF8.GetBytes(html);
            string text = "";
            for (int i = 0; i < buf.Length; ++i)
            {
                text += "%" + string.Format("{0:X2}", buf[i]);
            }
            return text;
        }

        private string PostDataToPage(string url,string searchtext,string cookies)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.KeepAlive = true;
            req.Method = "POST";
            req.Timeout = 1000 * 10;
            req.Referer = "http://btkitty.la/";
            req.Accept = "text/html, application/xhtml+xml, */*";
            req.ContentType = "application/x-www-form-urlencoded";
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
            req.Headers["Accept-Language"] = "zh-CN";

            req.AllowAutoRedirect = true;
            req.Headers.Add("Cookie", cookies);
            string param = "keyword=" + ToUTF8Str(searchtext);
            byte[] data = Encoding.Default.GetBytes(param);
            req.GetRequestStream().Write(data, 0, data.Length);

            HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
            using (StreamReader sr = new StreamReader(rep.GetResponseStream()))
            {
                string html = sr.ReadToEnd();
                return html;
            }
        }

        private string DownloadPage(string url,string searchtext)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.KeepAlive = true;
            req.Method = "GET";
            req.Timeout = 1000 * 10;
            req.Accept = "text/html, application/xhtml+xml, */*";
            req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)";
            req.Headers["Accept-Language"] = "zh-CN";
            req.AllowAutoRedirect = true;
            HttpWebResponse rep = req.GetResponse() as HttpWebResponse;
            string setcookie = rep.Headers.Get("Set-Cookie");
            string cookie = setcookie.Split(';')[0];
            return PostDataToPage(url,searchtext,cookie);
        }

        public MainForm()
        {
            InitializeComponent();

            Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 4, Screen.PrimaryScreen.WorkingArea.Height / 4);

            //txTextBox1.OnTextChanged = delegate
            //{
            //    txComboBox1.Items.AddRange(new string[] { "1", "2" });
            //    txComboBox1.DroppedDown = true;
            //};
        }

        private class BTInfo
        {
            public string Id { get; set; }
            public string Title { get; set; }
            public string Details { get; set; }
            public string Tag { get; set; }
            public string BTUrl { get; set; }
            public string MagneticUrl { get; set; }
        }

        private BTInfo GetInfo(HtmlNode dl)
        {
            BTInfo info = new BTInfo();
            HtmlNode node = dl.SelectSingleNode("dt/strong");
            if (node != null)
                info.Id = node.InnerText;
            node = dl.SelectSingleNode("dt/a");
            if (node != null)
            {
                info.Title = node.InnerText;
                info.BTUrl = node.Attributes["href"].Value;
            }
            node = dl.SelectSingleNode("dd[@class='option']/span/a");
            if (node != null)
            {
                info.MagneticUrl = node.Attributes["href"].Value;
                info.Tag = node.ParentNode.ParentNode.InnerText.Replace("[磁力链]", "");
                info.Tag = System.Web.HttpUtility.HtmlDecode(info.Tag);
            }
            node = dl.SelectSingleNode("dd[@class='flist']/p");
            if (node != null)
            {
                info.Details = node.InnerText;
            }

            return info;
        }
        private void txButton1_Click(object sender, EventArgs e)
        {
            string html = DownloadPage("http://btkitty.la/", txComboBox1.Text);
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
            string searchtext = "";
            HtmlNode node = root.SelectSingleNode("//div[@class='bar']");
            if (node != null)
                searchtext = node.InnerText;
            MessageBox.Show(searchtext);
            HtmlNodeCollection nodecollection = root.SelectNodes("//div[@class='list-box']/div[@class='list-con']/dl");
            if (nodecollection != null)
            {
                //List<BTInfo> infolist=new List<BTInfo>();
                foreach (HtmlNode dl in nodecollection)
                {
                    BTInfo info = GetInfo(dl);
                    ListViewItem item = new ListViewItem();
                    item.Text = info.Id;
                    item.SubItems.Add(info.Title);
                    item.SubItems.Add(info.Details);
                    item.SubItems.Add(info.Tag);
                    item.SubItems.Add(info.BTUrl);
                    item.SubItems.Add(info.MagneticUrl);
                    this.txListView1.Items.Add(item);
                }
            }
        }

        private Point m_prePoint = new Point() { X = 0, Y = 0 };

        private void txListView1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!(m_prePoint.X == e.X && m_prePoint.Y == e.Y))
            {
   
            }
        }

        private void txListView1_MouseEnter(object sender, EventArgs e)
        {

        }

        private void txListView1_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewItem lvi = (sender as ListView).GetItemAt(e.X, e.Y);
            if (lvi != null)
            {
                m_prePoint.X = e.X; m_prePoint.Y = e.Y;
                toolTip1.Show(lvi.SubItems[3].Text, txListView1, new Point(e.X, e.Y), 3000);
                toolTip1.Active = true;
            }
        }

        private void txComboBox1_TextChanged(object sender, EventArgs e)
        {
            //txComboBox1.DataSource = new List<string>(new string[] { "1", "2" });
            ////txComboBox1.Items.Clear();
            ////txComboBox1.Items.AddRange(new string[] { "1", "2" });
            //txComboBox1.DroppedDown = true;
        }
    }
}
